const router = require('koa-router')()

const dataServices = require('../controls/data')

// 主页数据接口
router.get('/data/index', async (ctx, next) => {
  let res = await dataServices.getIndexData()
  for (let i = 0; i < res.length; i++) {
    let ticketsArr = await dataServices.getTickets(res[i].type)
    // console.log('ticketArr',ticketsArr)
    res[i].tickets = ticketsArr.slice(0, 4)
    res[i].ticketsMore = ticketsArr.slice(4, 9)
  }
  // console.log('处理后的res',res)

  ctx.body = {
    code: 200,
    indexData: res,
    message: "数据请求成功"
  }
})

// 详情页的数据接口
router.get('/data/detail', async (ctx, next) => {
  console.log('后端id', ctx.request.query.id);
  let id = ctx.request.query.id
  // id没传递给后端时
  if (!id) {
    ctx.body = {
      code: 301,
      message: "该项目不存在",
      data: null,
      url:'/'
    }
    return 
  }

  function reviseStr(str) {
    // 将数据库中的summery字符串格式化为对象数组
    let res = []
    let strArr = str.split("-")
    for (let i = 0; i < strArr.length; i++) {
      let itemArr = strArr[i].split(",")
      let icon = itemArr[0].slice(itemArr[0].indexOf(":") + 1)
      let text = itemArr[1].slice(itemArr[1].indexOf(":") + 1)
      let descript = itemArr[2].slice(itemArr[2].indexOf(":") + 1)
      let item = {
        icon,
        text,
        descript
      }
      res.push(item)
    }
    return res
  }

  function reviseLabel(label) {
    // 格式化标签
    return label.split(",")
  }
  // res是一个数组
  let res = await dataServices.getDEtail(id)
  if(!res.length) {
    // 没查到数据时
    ctx.body = {
      code:301,
      message:"项目不存在或已被删除",
      data:null,
      url:'/'
    }
    return 
  }
  let swiperid = res[0].swiperImg
  let descriptid = res[0].descriptImg
  let summary = reviseStr(res[0].summary)
  let label = reviseLabel(res[0].labels)

  let swiperImgs = await dataServices.getSwiper(swiperid)
  let descriptImg = await dataServices.getImg(descriptid)
  res[0].swiperImg = swiperImgs
  res[0].descriptImg = descriptImg
  res[0].summary = summary
  res[0].label = label
  ctx.body = {
    code: 200,
    message: "成功",
    data: res[0]
  }
})

// 用户订单页数据接口
router.get('/data/order',async (ctx,next)=>{
    let userId = ctx.request.query.id
  console.log('order', ctx.request.query.id);
  if(!userId) {
    ctx.body={
      code:416,
      data:null,
      message:'用户不存在'
    }
    return 
  }
  let res = await dataServices.getOrderList(userId)
    ctx.body = {
      code:200,
      data:res,
      message:'查询成功'
    }
})
module.exports = router
